import uuid
import datetime
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy import Column, String, DateTime, Integer, Boolean
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()


def generate_uuid():
    return uuid.uuid4().hex


class DevOpsCollector(Base):
    """运维对象 数据采集"""
    __tablename__ = 'devops_collector'
    id = Column(String, primary_key=True, default=generate_uuid, comment='采集ID')

    devops_id = Column(String, nullable=False, comment='运维对象ID')
    name = Column(String, nullable=False, comment='采集名')
    type = Column(String, nullable=False, comment='采集类型')
    config = Column(JSONB, default={}, comment='采集配置')
    cron = Column(JSONB, nullable=True, comment='采集周期')

    size = Column(Integer, default=0, comment='数据量')
    count = Column(Integer, default=0, comment='数据条数')

    created_at = Column(DateTime, default=datetime.datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow,
                        comment='更新时间')


class DevOps(Base):
    """运维对象"""
    __tablename__ = 'devops'
    id = Column(String, primary_key=True, default=generate_uuid, comment='ID')

    name = Column(String, nullable=False, unique=True, comment='运维对象名')
    type = Column(String, nullable=False, comment='运维对象类型')
    tag = Column(JSONB, default=[], comment='运维对象标签')

    attribute = Column(JSONB, default={}, comment='运维对象属性')

    is_alive_check = Column(Boolean, default=False, comment='存活检查')
    is_monitor_check = Column(Boolean, default=False, comment='开启指标监控 部分类型暂不支持')

    score = Column(Integer, nullable=True, comment='健康得分')

    created_at = Column(DateTime, default=datetime.datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow,
                        comment='更新时间')

    collectors = relationship('DevOpsCollector', cascade='all, delete', order_by=DevOpsCollector.created_at.desc(),
                              lazy='dynamic')

    @property
    def size(self):
        return sum([item.size for item in self.collectors])

    @property
    def count(self):
        return sum([item.count for item in self.collectors])


class RelationView(Base):
    """关系视图"""
    __tablename__ = 'relation_view'
    id = Column(String, primary_key=True, default=generate_uuid, comment='ID')

    name = Column(String, nullable=False, unique=True, comment='关系视图名')
    score = Column(Integer, default=100, comment='健康得分')

    created_at = Column(DateTime, default=datetime.datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow,
                        comment='更新时间')
